<template>
  <md-field>
    <md-input-item v-model="form.uuid" :title="$t('token.transfer_to')" placeholder="0x"></md-input-item>
    <md-input-item v-model="form.num" type="money" :title="$t('token.transfer_num')"></md-input-item>
    <div style="padding: 20px 40px 0">
      <md-button type="primary" :loading="loading" @click="post" round plain>{{ $t('confirm') }}</md-button>
      <div style="padding-top: 30px; text-align: center">
        <md-button type="link" icon="address-book" @click="log">{{ $t('token.log') }}</md-button>
      </div>
    </div>
  </md-field>
  <Confirm ref="confirm" />
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { toast } from '@/style'
import { t } from '@/lang'
import { userInfo } from '@/model/user'
import { transfer } from '@/api/user'
import { packager, random } from '@/web3'
import Confirm from '@/components/confirm.vue'

const router = useRouter()
const form = ref({})
const confirm = ref(null)
const loading = ref(false)

// 更新一次
userInfo()

const post = () => {
  confirm.value.open([form.value.num, 'HWD'], form.value.uuid, 'center_gas_description', async() => {
    // 合并数据加入随机符
    const data = Object.assign({random: random()}, form.value)
    // 打包数据
    const pack = await packager(data)
    
    loading.value = true
    transfer(pack).then(res => {
      toast(t('ok'))
      userInfo()
    }).catch(err => {
      toast(err.message)
    }).finally(() => {
      loading.value = false
    })
  })
}

const log = () => {
  router.push('/token/log')
}
</script>